import { mainStore } from '../../../store/mainStore.js'

let store

const handleWebSocketMessage = (event) => {
  console.log('接收到 WebSocket 消息:', JSON.parse(event.data))
  store.eventData = event.data
}

export const connectWebSocket = () => {
  const ip = localStorage.getItem('wsIp')
  // const socket = new WebSocket(`${ip}/obstacles-event`)
  const socket = new WebSocket(`ws://localhost:8080`)

  socket.binaryType = 'arraybuffer' // 处理二进制数据

  socket.onopen = function () {
    store = mainStore()
    console.log(`事件检测ws服务已经连接: ${ip}/obstacles-event`)
  }

  socket.onmessage = handleWebSocketMessage

  socket.onclose = function (event) {
    console.log(`事件检测数据服务断开连接: ${ip}/obstacles-event`)
    console.log('断开原因:', event.code)
  }

  socket.onerror = function (error) {
    console.error('WebSocket 错误:', error)
  }
}
